package com.ruoyi.web.controller.common;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.ChatRole;
import com.ruoyi.system.service.IChatRoleService;
import io.github.asleepyfish.util.OpenAiUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.List;

@RestController
public class GPTController {
    @Autowired
    IChatRoleService chatRoleService;

    @Autowired
    RedisTemplate redisTemplate;

    @Value("${chatgpt.session-expiration-time}")
    Long expireTime;

    @RequestMapping("/startGpt")
    public String getGptAnswer(String content,Long roleId){
        ChatRole chatRole = chatRoleService.selectChatRoleById(roleId);
        String role = chatRole.getRole();
        String describeText = chatRole.getDescribeText();

        LoginUser loginUser = SecurityUtils.getLoginUser();
        String username = loginUser.getUsername();
        String roleKey = role+username;

        Boolean hasKey = redisTemplate.hasKey(roleKey);
        if (!hasKey){
            OpenAiUtils.createChatCompletion(describeText,roleKey);
            redisTemplate.opsForValue().set(hasKey,"finish");
            redisTemplate.expire(hasKey, Duration.ofDays(expireTime*60*1000));
        }

        List<String> resultList = OpenAiUtils.createChatCompletion(content, roleKey);
        return resultList.toString();

    }
}
